package com.sky.service.impl;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.BaseException;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.OrdersMapper;
import com.sky.result.PageResult;
import com.sky.service.*;
import com.sky.utils.BaiduMapsUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.*;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * TODO
 *
 * @Author Yjr
 * @Date 2025/5/27 9:53
 */
@Service
@Slf4j
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private AddressBookService addressBookService;
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private UserService userService;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private BaiduMapsUtil baiduMapsUtil;
    @Autowired
    private WebSocketServer webSocketServer;

    /**
     * 添加订单
     *
     * @param dto
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public OrderSubmitVO addOrder(OrdersSubmitDTO dto) {

        AddressBook addressBook = addressBookService.getById(dto.getAddressBookId());
        if (addressBook==null){
            throw new BaseException("地址为空,无法下单");
        }

        Long userId = BaseContext.getCurrentId();
        List<ShoppingCart> shoppingCarts = shoppingCartService.lambdaQuery().eq(ShoppingCart::getUserId, userId).list();
        if (CollectionUtils.isEmpty(shoppingCarts)){
            throw new BaseException("购物车为空,无法下单");
        }
        String address = addressBook.getProvinceName()+addressBook.getCityName()+addressBook.getDistrictName()+addressBook.getDetail();
        try {
            Double distance = baiduMapsUtil.getDistance(address);
            if (distance>5000){
                throw new BaseException("距离大于5公里无法下单");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        Orders orders = new Orders();
        BeanUtils.copyProperties(dto, orders);
        String number = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss"));
        orders.setNumber(number);
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setUserId(userId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
        User user = userService.getById(userId);
        orders.setUserName(user.getName());
        orders.setPhone(user.getPhone());

        orders.setAddress(address);
        orders.setConsignee(addressBook.getConsignee());
        boolean result = this.save(orders);
        if (!result){
            throw new BaseException("下单失败");
        }

        List<OrderDetail> orderDetails = shoppingCarts.stream().map(x -> {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(x, orderDetail);
            orderDetail.setId(null);
            orderDetail.setOrderId(orders.getId());
            return orderDetail;
        }).collect(Collectors.toList());
        boolean saveBatch = orderDetailService.saveBatch(orderDetails);
        if (!saveBatch){
            throw new BaseException("添加订单明细失败");
        }

        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(orders.getId())
                .orderNumber(number)
                .orderAmount(orders.getAmount())
                .orderTime(orders.getOrderTime())
                .build();

        Map<String,Object> map =new HashMap<>();
        map.put("type", 1);
        map.put("orderId", orders.getId());
        map.put("content", number);

        webSocketServer.sendToAllClient(JSONUtil.toJsonStr(map));

        return orderSubmitVO;
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    @Override
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userService.getById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    @Override
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = this.lambdaQuery().eq(Orders::getNumber,outTradeNo).one();

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        this.updateById(orders);
    }

    /**
     * 查询历史订单
     *
     * @param dto
     * @return
     */
    @Override
    public PageResult historyOrders(OrdersPageQueryDTO dto) {
        Page<Orders> page = this.lambdaQuery()
                .eq(dto.getStatus() != null, Orders::getStatus, dto.getStatus())
                .eq(StringUtils.hasLength(dto.getNumber()), Orders::getNumber, dto.getNumber())
                .eq(StringUtils.hasLength(dto.getPhone()), Orders::getPhone, dto.getPhone())
                .between(dto.getBeginTime()!=null&&dto.getEndTime()!=null,Orders::getOrderTime,dto.getBeginTime(),dto.getEndTime())
                .page(new Page<>(dto.getPage(), dto.getPageSize()));
        List<Orders> ordersList = page.getRecords();

        if (CollectionUtils.isNotEmpty(ordersList)) {
            List<OrderVO> ordersVoList = ordersList.stream().map(x -> {
                OrderVO vo = new OrderVO();
                BeanUtils.copyProperties(x, vo);
                List<OrderDetail> orderDetailList = orderDetailService.lambdaQuery().eq(OrderDetail::getOrderId, x.getId()).list();
                vo.setOrderDetailList(orderDetailList);
                if (CollectionUtils.isNotEmpty(orderDetailList)) {
                    StringBuilder orderDishes = new StringBuilder();
                    orderDetailList.forEach(j->{
                        orderDishes.append(j.getName()+"*"+j.getNumber());
                    });
                    vo.setOrderDishes(orderDishes.toString());
                }
                return vo;
            }).collect(Collectors.toList());
            return new PageResult(page.getTotal(),ordersVoList);
        }

        return new PageResult();
    }

    /**
     * 查询订单详情
     *
     * @param id
     * @return
     */
    @Override
    public OrderVO findOrdersById(Long id) {
        Orders orders = this.getById(id);
        List<OrderDetail> orderDetailList = orderDetailService.lambdaQuery().eq(OrderDetail::getOrderId, id).list();
        OrderVO vo=new OrderVO();
        BeanUtils.copyProperties(orders, vo);
        vo.setOrderDetailList(orderDetailList);

        return vo;
    }

    /**
     * 取消订单
     *
     * @param dto
     */
    @Override
    public void cancelOrders(OrdersCancelDTO dto) {
        Orders orders = Orders.builder()
                .id(dto.getId())
                .cancelReason(dto.getCancelReason())
                .cancelTime(LocalDateTime.now())
                .status(Orders.CANCELLED).build();
        boolean result = this.updateById(orders);
        if (!result){
            throw new BaseException("取消失败");
        }
    }

    /**
     * 各个状态的订单数量统计
     *
     * @return
     */
    @Override
    public OrderStatisticsVO statistics() {
        Long toBeConfirmed = this.lambdaQuery().in(Orders::getStatus, Arrays.asList(1, 2))
                .count();

        Long confirmed = this.lambdaQuery().eq(Orders::getStatus, Orders.CONFIRMED)
                .count();

        Long deliveryInProgress = this.lambdaQuery().eq(Orders::getStatus, Orders.DELIVERY_IN_PROGRESS)
                .count();

        return OrderStatisticsVO.of(toBeConfirmed.intValue(),confirmed.intValue(),deliveryInProgress.intValue());
    }

    /**
     * 再来一单
     *
     * @param id
     */
    @Override
    public void repetitionOrders(Long id) {
        Orders orders = this.getById(id);
        if (orders==null){
            throw new BaseException("订单不存在");
        }

        orders.setId(null);
        String number = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss"));
        orders.setNumber(number);
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
        orders.setCancelReason(null);
        orders.setRejectionReason(null);
        orders.setCancelTime(null);
        orders.setEstimatedDeliveryTime(null);
        orders.setDeliveryTime(null);

        if (!this.save(orders)){
            throw new BaseException("再来一单失败");
        }

        List<OrderDetail> orderDetailList = orderDetailService.lambdaQuery().eq(OrderDetail::getOrderId, id).list();
        try {
            orderDetailList.forEach(x->{
                x.setId(null);
                x.setOrderId(orders.getId());
                orderDetailService.save(x);
            });
        } catch (Exception e) {
            throw new RuntimeException("添加失败");
        }
    }

    /**
     * 接单
     *
     * @param dto
     */
    @Override
    public void confirm(OrdersConfirmDTO dto) {
        Orders orders = Orders.builder().id(dto.getId()).status(Orders.CONFIRMED).build();
        boolean result = this.updateById(orders);
        if (!result){
            throw new BaseException("接单失败");
        }

    }

    /**
     * 拒单
     *
     * @param dto
     */
    @Override
    public void rejection(OrdersRejectionDTO dto) {
        Orders orders = Orders.builder()
                .id(dto.getId())
                .rejectionReason(dto.getRejectionReason())
                .cancelReason(dto.getRejectionReason())
                .cancelTime(LocalDateTime.now())
                .status(Orders.CANCELLED)
                .build();

        boolean result = this.updateById(orders);
        if (!result){
            throw new BaseException("拒单失败");
        }
    }

    /**
     * 派送订单
     *
     * @param id
     */
    @Override
    public void delivery(Long id) {
        Orders orders = Orders.builder()
                .id(id)
                .status(Orders.DELIVERY_IN_PROGRESS)
                .estimatedDeliveryTime(LocalDateTime.now().plusMinutes(12))
                .build();

        boolean result = this.updateById(orders);
        if (!result){
            throw new BaseException("派送失败");
        }
    }

    /**
     * 完成订单
     *
     * @param id
     */
    @Override
    public void complete(Long id) {
        Orders orders = Orders.builder()
                .id(id)
                .status(Orders.COMPLETED)
                .deliveryTime(LocalDateTime.now())
                .build();

        boolean result = this.updateById(orders);
        if (!result){
            throw new BaseException("修改完成状态失败");
        }
    }

    /**
     * 客户催单
     *
     * @param id
     * @return
     */
    @Override
    public void reminder(Long id) {
        Orders orders = this.getById(id);

        Map<String,Object> map =new HashMap<>();
        map.put("type", 2);
        map.put("orderId", id);
        map.put("content", orders.getNumber());

        webSocketServer.sendToAllClient(JSONUtil.toJsonStr(map));

    }
}
